package com.zprmb.udzt;

import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.util.BitmapUtils;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleySingleton;
import com.zprmb.udzt.view.LoadingDialog;
import com.zprmb.udzt.vo.AuthFailureError;
import com.zprmb.udzt.vo.Request.Method;
import com.zprmb.udzt.vo.Response;
import com.zprmb.udzt.vo.VolleyError;
import com.zprmb.udzt.vo.toolbox.JsonObjectRequest;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class V6Register_Confirm extends BaseActivity implements OnClickListener {
    private EditText user_passord, user_recommend;
    private Button btn_next;
    private LoadingDialog dialog;
    private ImageView img_reg_bg;
    private ImageView pass;
    private TextView tv_regist_info;
    private CheckBox checkBox;
    private TextView jump_login;
    private Map<String, String> headers = new HashMap<String, String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.v6_regist_confirm);
        BbtApplication.getInstance().addActvity(this);
        dialog = new LoadingDialog(this);
        setgoback(this);
        setTitle("注册", this);
        initView();
    }

    private void initView() {
        // TODO Auto-generated method stub
        pass = (ImageView) findViewById(R.id.img_pass);
        img_reg_bg = (ImageView) findViewById(R.id.img_reg_bg);
        jump_login = (TextView) findViewById(R.id.jump_login);
        user_passord = (EditText) findViewById(R.id.user_passord);
        user_recommend = (EditText) findViewById(R.id.user_recommend);
        btn_next = (Button) findViewById(R.id.btn_next);
        checkBox = (CheckBox) findViewById(R.id.check);
        img_reg_bg.setImageBitmap(BitmapUtils.readBitMap(this, R.drawable.v6_login_bg));
        tv_regist_info = (TextView) findViewById(R.id.tv_regist_info);
        tv_regist_info.setOnClickListener(this);
        btn_next.setOnClickListener(this);
        pass.setOnClickListener(this);
        jump_login.setOnClickListener(this);
        setEditTextInhibitInputSpace(user_passord);
        checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (user_passord.getText().toString().length() >= 6 && isChecked && user_recommend.getText().length() >= 1) {
                    btn_next.setBackgroundResource(R.drawable.v6button);
                    btn_next.setEnabled(true);
                } else {
                    btn_next.setBackgroundResource(R.drawable.btn_unclick);
                    btn_next.setEnabled(false);
                }
            }
        });
        user_recommend.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if (user_passord.getText().toString().length() >= 6 && checkBox.isChecked() && user_recommend.getText().length() >= 1) {
                    btn_next.setBackgroundResource(R.drawable.v6button);
                    btn_next.setEnabled(true);

                } else {
                    btn_next.setBackgroundResource(R.drawable.btn_unclick);
                    btn_next.setEnabled(false);
                }
            }
        });
        user_passord.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if (user_passord.getText().toString().length() >= 6 && checkBox.isChecked() && user_recommend.getText().length() >= 1) {
                    btn_next.setBackgroundResource(R.drawable.v6button);
                    btn_next.setEnabled(true);

                } else {
                    btn_next.setBackgroundResource(R.drawable.btn_unclick);
                    btn_next.setEnabled(false);
                }
                if (user_passord.getText().toString().equals("")) {
                    pass.setVisibility(View.GONE);
                } else {
                    pass.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void showDialog() {
        if (dialog.isShowing() == false & !V6Register_Confirm.this.isFinishing()) {
            dialog.show();
        }
    }

    private void dissmissDialog() {
        if (dialog != null & !V6Register_Confirm.this.isFinishing()) {
            dialog.dismiss();
        }
    }

    private void regist() {
        showDialog();
        AjaxParams params = new AjaxParams();
        params.put("source", getMetaData(V6Register_Confirm.this));
		params.put("mobile", getIntent().getStringExtra("mobile"));

//        params.put("mobile", "13674610754");
        params.put("password", user_passord.getText().toString());
        params.put("ref", user_recommend.getText().toString());
        JsonObjectRequest json = new JsonObjectRequest(Method.POST,
                Constant.URL + "/api/v6/register/confirmRegister?" + params.toString(), null, new Response.Listener<JSONObject>() {
            public void onResponse(JSONObject response) {
                dissmissDialog();
                Log.e("下一步", response.toString());
                if (response.optInt("success") == 1) {
                    JSONObject json1 = response.optJSONObject("data");

                    Gson gson = new Gson();
                    Editor editor = getShare().edit();
                    editor.putString(
                            "token",
                            json1.optString(
                                    "token"));
                    editor.putString(
                            "mobile",
                            json1.optString(
                                    "mobile"));
                    editor.putString(
                            "userId",
                            json1.optString(
                                    "userId"));
                    editor.putString(
                            "qrcode",
                            json1.optString(
                                    "userCode"));
                    editor.commit();
                    Intent intent = new Intent(V6Register_Confirm.this, MainActivity.class);
                    intent.putExtra("register", 1);
                    startActivity(intent);

                } else {
                    ToastUtil.showCenterToast(V6Register_Confirm.this, response.optString("comment"));
                }
            }

        }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
                dissmissDialog();

            }
        }) {
            public Map<String, String> getHeaders() throws AuthFailureError {
                headers.put("appVersion", getAppVersion());
                headers.put("client", "android");
//				headers.put("deviceToken", getdeviceId());
                headers.put("deviceToken", getdevice_token());
                headers.put("mobileType", getDeviceType());
                headers.put("deviceID", getdeviceId());
                return headers;
            }
        };
        VolleySingleton.getInstance(V6Register_Confirm.this).addToRequestQueue(json);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent = null;
        switch (v.getId()) {

            case R.id.btn_next:
                regist();
                break;
            case R.id.jump_login:
                Intent intent3 = new Intent(V6Register_Confirm.this, V6LoginActivity.class);
                intent3.putExtra("close", 1);
                startActivity(intent3);
                break;
            case R.id.tv_regist_info:
                Intent intent2 = new Intent(V6Register_Confirm.this, V4WebViewRegisterActivity.class);
                intent2.putExtra("url", "landing/regAgreement?app=true&appversion=true");
                intent2.putExtra("title", "优点智投平台服务协议");
                intent2.putExtra("share", 1);
                startActivity(intent2);
                break;
            case R.id.img_pass:
                if (user_passord.getTransformationMethod().equals(PasswordTransformationMethod
                        .getInstance())) {
                    user_passord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    pass.setBackgroundResource(R.drawable.yan1);
                } else {
                    user_passord.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    pass.setBackgroundResource(R.drawable.yan2);
                }
                break;
        }
    }

}
